package db;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import db.*;

public class UserEdited extends HttpServlet {
	public void doPost(HttpServletRequest request,HttpServletResponse response)
										throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		DatabaseConnector DBConnect = new DatabaseConnector(DatabaseConnector.getDatabaseType());


		out.println("<html><head><title>User Modification -- Result</title>");
		out.println("<script type=\"text/javascript\" src=\"../userManager.js\"></script>");
		out.println("</head><body>");


		String[] in = {"*"};
		Object[] check = DBConnect.selectSQL("Users",in,"username",request.getParameter("username")); // Retrieve connection information
		try{
			if (check[0].equals("null")){ }//triggers catch if does not exist => username changed
			if (!request.getParameter("username").equals(request.getParameter("oldUsername"))){ //tried using a preexisting username
				out.println("<body onload=directToEdit(\"?"
					+ "username=" + request.getParameter("username")
					+ "&password=" + request.getParameter("password")
					+ "&email=" + request.getParameter("email")
					+ "&groups=" + request.getParameter("groups")
					+ "&oldUsername=" + request.getParameter("oldUsername")
					+ "&loadCase=existent"
					+ "\")>Redirecting you to Edit User...</body></html>");
			} else {//Username did not change
				//update tables

				//start of changes------------------------------------------------------------------------------
				String pwd = null;
				try{
					java.security.MessageDigest md5Digest = java.security.MessageDigest.getInstance("MD5");
					byte[] bytes = request.getParameter("password").getBytes();
					pwd = new String(md5Digest.digest(bytes));
				} catch (java.security.NoSuchAlgorithmException nsae) {
					System.out.println(nsae);
				}
                                //Update tablename, column name, column value, Where fieldname = fieldvalue;
				DBConnect.updateSQL("Users",new String[]{ "password" }, new String[] { pwd },"username",request.getParameter("username"));
				//end of changes----------------------------------------------------------------

				DBConnect.updateSQL("User_Info",new String[]{ "email" }, new String[] { request.getParameter("email") },"username",request.getParameter("username"));
				DBConnect.deleteSQL("User_Roles","username",request.getParameter("username"));
				makeGroups(request,DBConnect);

				out.println("<body><h3>User '"+ request.getParameter("username") +"' successfully modified!</h3>");
				out.println("<a href=\"ListUsers\">Return to User Listing</a></body></html>");
			}
		} catch (NullPointerException npe) {
			//add new user stuff
			in = new String[]{ (request.getParameter("username")),(request.getParameter("password")) };
			String[] params = {"username","password"};
			DBConnect.insertSQL("Users",params,in);

			in = new String[] {request.getParameter("username"),request.getParameter("email")};
			params[1] = "email";
			DBConnect.insertSQL("User_Info",params,in);

			//insert groups
			makeGroups(request,DBConnect);

			//drop all old user stuff
			DBConnect.deleteSQL("User_Info","username",request.getParameter("oldUsername"));
			DBConnect.deleteSQL("User_Roles","username",request.getParameter("oldUsername"));
			DBConnect.deleteSQL("Users","username",request.getParameter("oldUsername"));

			out.println("<body><h3>User '"+ request.getParameter("username") +"' was successfully modified!</h3>");
			out.println("<a href=\"ListUsers\">Return to User Listing</a></body></html>");
		}
	}

	private void makeGroups(HttpServletRequest request, DatabaseConnector DBConnect){
		String reqGroups = request.getParameter("groups");
		String[] in;
		if (!reqGroups.equals("")) {
			String[] groups = reqGroups.split(";");
			for (int i=0;i<groups.length;i++){
				in = new String[]{ request.getParameter("username"),groups[i] };
				DBConnect.insertSQL("User_Roles",new String[] { "username","role" },in);
			}
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
		doPost(request, response);
	}
}